package com.shenmazg6.controller;

import com.shenmazg6.pojo.TbProduct;
import com.shenmazg6.service.TbProductService;
import com.shenmazg6.utils.ResultResponse;
import com.shenmazg6.vo.PageInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 军哥
 * @version 1.0
 * @description: TbProductController
 * @date 2022/12/19 16:04
 */

@RestController
@Slf4j
@RequestMapping(value = "/product")
public class TbProductController {

    @Autowired
    TbProductService tbProductService;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @PostMapping(value = "/list")
    public ResultResponse list(@RequestBody PageInfoVo pageInfoVo) {
        return tbProductService.ListByPage(pageInfoVo);
    }

    @PostMapping(value = "/search")
    public ResultResponse search() {
        PageRequest pageable = PageRequest.of(0, 10);
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        RangeQueryBuilder queryBuilder = QueryBuilders.rangeQuery("updateTime")
                .format("yyyy-MM-dd HH:mm:ss")
                .timeZone("GMT+8")
                .gte("2022-11-23 10:58:13").lte("2022-11-23 10:59:40")
                .includeLower(true).includeUpper(true);

        NativeSearchQuery searchQuery = builder.withPageable(pageable)
                .withQuery(queryBuilder)
                .build();

        SearchHits<TbProduct> search = elasticsearchRestTemplate.search(searchQuery, TbProduct.class);
        List<SearchHit<TbProduct>> searchHits = search.getSearchHits();

        List<TbProduct> collect = searchHits.stream().map(item -> {
            TbProduct content = item.getContent();
            return content;
        }).collect(Collectors.toList());

        return ResultResponse.SUCCESS(collect);
    }

}
